import 'package:flutter/material.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:hao_ke/pages/auth/auth.dart';
import 'package:hao_ke/pages/utils/string_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../consts/url_const.dart';
import '../utils/dio_http.dart';
import '../utils/shared_preferences.dart';
import 'utils/scoped_model_helper.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {


  bool showIcons = false;

  TextEditingController userNameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录'),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Container(
          padding: const EdgeInsets.only(top: 100, left: 40, right: 40),
          child: ListView(
            children: [
              TextField(
                style: TextStyle( fontSize: 16),
                controller: userNameController,
                decoration: const InputDecoration(
                    labelText: '用户名',
                    hintText: '请输入用户名',
                    hintStyle: TextStyle(
                      color: Colors.grey,
                    )),
              ),
              SizedBox(height: 20),
              TextField(
                style: TextStyle(fontSize: 16),
                obscureText: !showIcons,
                controller: passwordController,
                decoration: InputDecoration(
                  labelText: '密码',
                  hintText: '请输入密码',
                  hintStyle: TextStyle(
                    color: Colors.grey,
                  ),
                  suffixIcon: IconButton(
                    icon: Icon(
                        showIcons ? Icons.visibility : Icons.visibility_off),
                    onPressed: () {
                      setState(() {
                        showIcons = !showIcons;
                      });
                    },
                    color: Colors.blue,
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.only(right: 20, left: 20),
                margin: const EdgeInsets.only(top: 40),
                child: FilledButton(
                  onPressed: () {
                    _loginHandler();
                  },
                  child: Container(
                    child: Text(
                      '登 录',
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 20),
                    ),
                  ),
                  style: ButtonStyle(
                      maximumSize: MaterialStateProperty.all(Size(100, 50)),
                      backgroundColor: MaterialStateProperty.all(
                          Color.fromRGBO(100, 10, 255, 0.6)),
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10),
                      ))),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void setState(VoidCallback fn) {
    SharedPreferences.setMockInitialValues({});
  }

  void _loginHandler() async {
    // 获取用户名密码发送登录请求
    String userName = userNameController.text;
    String password = passwordController.text;
    if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
      showToast("用户名或密码不能为空",
          context: context,
          position: StyledToastPosition.center,
          backgroundColor: Colors.pink[300]);
      return;
    }

    var response =
        await DioHttp().init(context, UrlConst.basic).post(UrlConst.login, params: {
      "username": userName,
      "password": password,
      "grant_type": "password",
    });
    String token = response['access_token'];
    SharedPreferencesUtils.getInstance().setString( "token", token);
    var userInfo = await DioHttp().init(context, token).get(UrlConst.user_info);
    await SharedPreferencesUtils.getInstance().setString( "name", userInfo['name'].toString());
    ScopedModelHelper.getModel<AuthModel>(context).login(token, userInfo['name'].toString(),context);
    showToast("登录成功",
        context: context,
        position: StyledToastPosition.center,
        backgroundColor: Colors.green[300]);
    Navigator.of(context).pushReplacementNamed('/');
  }
}
